package com.abc.tool;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringTool {
	/**
	 * 字符串的首字符大写,例如 "xdemo"转为Xdemo
	 * @return
	 */
	public static String toFirstUpperCase(String s){
		String first = s.substring(0, 1).toUpperCase();
		String rest = s.substring(1, s.length());
		return  new StringBuffer(first).append(rest).toString();
	}
	
	/**
	 * 把文件路径转为包路径 ，例如 "business/product" 转为"business.product"
	 * @param s
	 * @return
	 */
	public static String filePathToPackagePath(String s){
		return s.replaceAll("/", ".");
	}
	
	/**
	 * 把字符串中的字符用正则表达式替换
	 * @param fileContent
	 * @param patternString
	 * @param replace
	 * @return
	 */
	public  static String replaceAll(String fileContent, String patternString, String replace) {  
        String str = "";  
        Matcher m = null;  
        Pattern p = null;  
        try {  
            p = Pattern.compile(patternString);  
            m = p.matcher(fileContent);  
            str = m.replaceAll(replace);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            m = null;  
            p = null;  
        }
        return str;  
	  
	}
	
	public static String[] ListToStringArray(List list){
		String [] strings =new String[list.size()];
		for (int i = 0; i < strings.length; i++) {
			strings[i] = list.get(i).toString();
		}
		return strings;
	}
	
	public static String getRandomString(int length) { //length表示生成字符串的长度
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	} 
	/**
	 * 
	 * @param dateString
	 * @param format
	 * @return
	 */
	public static String date2String(Date date,String pattern){
		if(pattern==null||pattern.isEmpty())
			pattern="yyyy-MM-dd HH:mm:ss";
		if(date==null){
			return "";
		}
		return new SimpleDateFormat(pattern).format(date);
	}
	
	/**
	 * 字符串转时间
	 * @param dateString
	 * @param pattern
	 * @return
	 */
	public static Date string2Date(String dateString,String pattern){
		if(pattern==null||pattern.isEmpty())
			pattern="yyyy-MM-dd HH:mm:ss.SSS";
		try {
			return new SimpleDateFormat(pattern).parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
